package com.tjec.project.projectWorkbench.controller;

import com.tjec.common.constant.Constants;
import com.tjec.common.utils.SecurityUtils;
import com.tjec.common.utils.StringUtils;
import com.tjec.framework.web.controller.BaseController;
import com.tjec.framework.web.domain.AjaxResult;
import com.tjec.framework.web.domain.TreeSelect;
import com.tjec.framework.web.domain.TreeSelectNew;
import com.tjec.framework.web.page.TableDataInfo;
import com.tjec.project.businessWorkbench.domain.*;
import com.tjec.project.businessWorkbench.dto.BmsAttachmentDto;
import com.tjec.project.businessWorkbench.service.*;
import com.tjec.project.projectWorkbench.domain.BmsProject;
import com.tjec.project.projectWorkbench.domain.BmsProjectMember;
import com.tjec.project.projectWorkbench.service.IBmsProjectMemberHistoryService;
import com.tjec.project.projectWorkbench.service.IBmsProjectMemberService;
import com.tjec.project.projectWorkbench.service.IBmsProjectService;
import com.tjec.project.system.domain.BmsAttachment;
import com.tjec.project.system.mapper.BmsAttachmentMapper;
import com.tjec.project.system.service.IBmsAttachmentService;
import com.tjec.project.system.service.IBmsMdBusinessCategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 *  文档查询Controller
 *
 * @author cjj
 * @date 2020-04-14
 */
@Api(value = "项目主页-文档查询", tags = {"项目主页-文档查询接口"})
@RestController
@RequestMapping("/project/fileQuery")
public class BmsProjectDocQueryController extends BaseController{

    @Autowired
    private IBmsProjectDocService bmsProjectDocService;

    @Autowired
    private IBmsBusinessService bmsBusinessService;

    @Autowired
    private IBmsProjectService bmsProjectService;

    @Autowired
    private IBmsProjectDocCatalogService bmsProjectDocCatalogService;

    @Autowired
    private IBmsProjectMemberService bmsProjectMemberService;

    @Autowired
    private IBmsMdBusinessCategoryService bmsMdBusinessCategoryService;

    @Autowired
    private IBmsBusinessPickupService bmsBusinessPickupService;

    @Autowired
    private IBmsBusinessDocArchiveService bmsBusinessDocArchiveService;

    @Autowired
    private BmsAttachmentMapper bmsAttachmentMapper;
    @Value("${sftp.http}")
    private String http;
    @Value("${sftp.ip}")
    private String ip;
  /*
     * 文档查询列表
     */
    /*@ApiOperation("文档查询列表")
//    @PreAuthorize("@ss.hasPermi('project:fileQuery:list')")
    @GetMapping("/list")
    public TableDataInfo list(BmsProjectDoc bmsProjectDoc)
    {
        bmsProjectDocService.parsingParamBmsProjectDoc(bmsProjectDoc);
        startPage();
        List<BmsProjectDoc> list = new ArrayList<>();
        if(StringUtils.isNotBlank(bmsProjectDoc.getProjectId())||StringUtils.isNotBlank(bmsProjectDoc.getCatalogId())||!CollectionUtils.isEmpty(bmsProjectDoc.getBusinessIds())){
            list = bmsProjectDocService.selectAllProjectDocQueryList(bmsProjectDoc);
        }
        list.forEach(item -> {
//            BmsBusiness bmsBusiness = bmsBusinessService.selectBmsBusinessByGuid(item.getBusinessId());
//            item.setBusinessName(bmsBusiness!=null?bmsBusiness.getName():"");
            List<BmsAttachmentDto> attachments = item.getAttachments();
            attachments.forEach(it -> {
                if (StringUtils.isNotBlank(it.getFileId())) {
                    it.setStoragePath(http + ip + Constants.RESOURCE_PREFIX + it.getStoragePath());
                }
            });
        });
        return getDataTable(list);
    }*/

    @ApiOperation("项目文档收资列表")
//    @PreAuthorize("@ss.hasPermi('project:fileQuery:list')")
    @GetMapping("/pickupList")
    public TableDataInfo list(BmsBusinessPickup bmsBusinessPickup)
    {
        if(StringUtils.isBlank(bmsBusinessPickup.getBusinessId())){
            return null;
        }
        BmsProjectDocCatalog docCatalog = bmsProjectDocCatalogService.selectBmsProjectDocCatalogByGuid(bmsBusinessPickup.getBusinessId());
        bmsBusinessPickup.setBusinessId(docCatalog.getBusinessId());
        startPage();
        List<BmsBusinessPickup> list = bmsBusinessPickupService.selectProjectDocQueryList(bmsBusinessPickup);
        /*for (BmsBusinessPickup businessPickup : list) {
            BmsBusiness bmsBusiness = bmsBusinessService.selectBmsBusinessByGuid(businessPickup.getBusinessId());
            businessPickup.setBusinessName(bmsBusiness!=null?bmsBusiness.getName():"");
        }*/
        return getDataTable(list);
    }

    /**
     * 查询项目文档 列表
     */
    @ApiOperation("项目文档成果校审列表")
    //@PreAuthorize("@ss.hasPermi('businessWorkbench:doc:list')")
    @GetMapping("/businessDocList")
    public TableDataInfo businessDocList(BmsProjectDoc bmsProjectDoc)
    {
        bmsProjectDocService.parsingParamBmsProjectDoc(bmsProjectDoc);
        startPage();
        List<BmsProjectDoc> list = new ArrayList<>();
        if(!CollectionUtils.isEmpty(bmsProjectDoc.getGuids())||StringUtils.isNotBlank(bmsProjectDoc.getCatalogId())||!CollectionUtils.isEmpty(bmsProjectDoc.getBusinessIds())){
            list = bmsProjectDocService.selectAllProjectDocQueryList(bmsProjectDoc);
        }
        return getDataTable(list);
    }

    /**
     * 查询项目文档 列表成果校审
     */
    @ApiOperation("项目文档成果校审列表")
    //@PreAuthorize("@ss.hasPermi('businessWorkbench:doc:list')")
    @GetMapping("/businessDocListResult")
    public TableDataInfo businessDocListResult(BmsProjectDoc bmsProjectDoc)
    {
        bmsProjectDocService.parsingParamBmsProjectDoc(bmsProjectDoc);
        startPage();
        List<BmsProjectDoc> list = new ArrayList<>();
        if(StringUtils.isNotBlank(bmsProjectDoc.getProjectId())||StringUtils.isNotBlank(bmsProjectDoc.getCatalogId())||!CollectionUtils.isEmpty(bmsProjectDoc.getBusinessIds())){
            BmsProjectDoc bmsProjectDocEntity =new BmsProjectDoc();
            bmsProjectDocEntity.setType("3");
            List<BmsAttachmentDto> attachmentsList = bmsAttachmentMapper.selectBmsAttachmentByBizIds(bmsProjectDoc.getGuids());
            bmsProjectDocEntity.setAttachments(attachmentsList);
            list.add(bmsProjectDocEntity);
        }
        list.forEach(item -> {
            BmsBusiness bmsBusiness = bmsBusinessService.selectBmsBusinessByGuid(item.getBusinessId());
            item.setBusinessName(bmsBusiness!=null?bmsBusiness.getName():"");
            List<BmsAttachmentDto> attachments = item.getAttachments();
            attachments.forEach(it -> {
                if (StringUtils.isNotBlank(it.getFileId())) {
                    it.setStoragePath(http + ip + Constants.RESOURCE_PREFIX + it.getStoragePath());
                }
            });
        });
        return getDataTable(list);
    }

    /**
     * 查询资料归档列表
     */
    @ApiOperation("查询资料归档列表")
//    @PreAuthorize("@ss.hasPermi('businessWorkbench:archive:list')")
    @GetMapping("/listInDoc")
    public TableDataInfo listInDoc(BmsBusinessDocArchive bmsBusinessDocArchive)
    {
        BmsProjectDocCatalog docCatalog = bmsProjectDocCatalogService.selectBmsProjectDocCatalogByGuid(bmsBusinessDocArchive.getBusinessId());
        bmsBusinessDocArchive.setBusinessId(docCatalog.getBusinessId());
        startPage();
        List<BmsBusinessDocArchive> list = bmsBusinessDocArchiveService.selectBmsBusinessDocArchiveListInDocQuery(bmsBusinessDocArchive);
        for (BmsBusinessDocArchive item : list) {
            BmsBusiness bmsBusiness = bmsBusinessService.selectBmsBusinessByGuid(item.getBusinessId());
            item.setBusinessName(bmsBusiness!=null?bmsBusiness.getName():"");
        }
        return getDataTable(list);
    }

    /**
     * 获取某个项目文档查询左侧树形结构
     */
    /*@ApiOperation("获取某个项目文档查询左侧树形结构")
//    @PreAuthorize("@ss.hasPermi('project:fileQuery:tree')")
    @GetMapping("/tree")
    public AjaxResult tree(BmsProjectDoc bmsProjectDoc)
    {
        TreeSelectNew tree = new TreeSelectNew();
        if(StringUtils.isNotBlank(bmsProjectDoc.getProjectId())){
            BmsProject bmsProject = bmsProjectService.selectBmsProjectByGuid(bmsProjectDoc.getProjectId());
            tree.setId(bmsProjectDoc.getProjectId());
            tree.setLabel(bmsProject.getName());
            List<BmsBusiness> bmsBusinesss = bmsBusinessService.selectBmsBusinessByProjectId(bmsProjectDoc.getProjectId());
            List<TreeSelectNew> treeSelectNews = new ArrayList<>();
            //判断当前登录是是否为招标组长或组员
            Set<String> engineeringBiddingList = bmsMdBusinessCategoryService.selectEngineeringBidding();
            String currentUserId = SecurityUtils.getLoginUser().getUser().getUserId();
            for (BmsBusiness business : bmsBusinesss) {
                BmsProjectDocCatalog bmsProjectDocCatalog = new BmsProjectDocCatalog();
                if(!(bmsProjectMemberService.isTenderMembers(currentUserId, business)&&engineeringBiddingList.contains(business.getBusinessCategoryId()))){
                    bmsProjectDocCatalog.setBusinessId(business.getGuid());
                    List<BmsProjectDocCatalog> bmsProjectDocCatalogs = bmsProjectDocCatalogService.selectBmsProjectDocCatalogList(bmsProjectDocCatalog);
                    if (bmsProjectDocCatalogs != null && bmsProjectDocCatalogs.size() > 0) {
                        bmsProjectDocCatalogs.forEach(item -> {
                            if("0".equals(item.getIsEdit())) {
                                Integer res = bmsProjectDocCatalogService.selectPickUpCounts(business.getGuid());
                                item.setCounts(res == null ? 0 : res);
                            }else if("1".equals(item.getIsEdit())) {
                                Integer res = bmsProjectDocCatalogService.selectDocCounts(item.getGuid());
                                item.setCounts(res == null ? 0 : res);
                            }else if("2".equals(item.getIsEdit())) {
                                Integer res = bmsProjectDocCatalogService.selectArchiveCounts(business.getGuid());
                                item.setCounts(res == null ? 0 : res);
                            }else if("3".equals(item.getIsEdit())) {
                                Integer res = bmsProjectDocCatalogService.selectResultCounts(item.getGuid());
                                item.setCounts(res == null ? 0 : res);
                            }
                        });
                    }
                    treeSelectNews.addAll(bmsProjectDocCatalogService.buildDocCatalogTreeSelect(bmsProjectDocCatalogs));
                }
            }
            tree.setCounts(treeSelectNews.stream().collect(Collectors.summingInt(TreeSelectNew::getCounts)));
            tree.setChildren(treeSelectNews);
        }
        return AjaxResult.success(tree);
    }*/

    /**
     * 获取某个项目文档查询左侧树形结构(动态加载)
     */
    @ApiOperation("获取某个项目文档查询左侧树形结构")
//    @PreAuthorize("@ss.hasPermi('project:fileQuery:tree')")
    @GetMapping("/tree")
    public AjaxResult tree(BmsProjectDoc bmsProjectDoc)
    {
        List<TreeSelectNew> trees = new ArrayList<>();
        List<TreeSelectNew> treeSelectNews = new ArrayList<>();
        if(StringUtils.isNotBlank(bmsProjectDoc.getProjectId())){
            TreeSelectNew tree = new TreeSelectNew();
            if(StringUtils.isBlank(bmsProjectDoc.getLevel())||bmsProjectDoc.getLevel().equals("0")){
                BmsProject bmsProject = bmsProjectService.selectBmsProjectByGuid(bmsProjectDoc.getProjectId());
                tree.setId(bmsProjectDoc.getProjectId());
                tree.setLabel(bmsProject.getName());
                bmsProjectDoc.setCatalogId(bmsProjectDoc.getProjectId());
                bmsProjectDocService.parsingParamBmsProjectDoc(bmsProjectDoc);
                tree.setCounts(bmsProjectDocService.countProjectDocCatalog(bmsProjectDoc));
                tree.setChildren(treeSelectNews);
                trees.add(tree);
            }else if(bmsProjectDoc.getLevel().equals("1")){
                List<BmsBusiness> bmsBusinesss = bmsBusinessService.selectBmsBusinessByProjectId(bmsProjectDoc.getProjectId());
                //判断当前登录是是否为招标组长或组员
                Set<String> engineeringBiddingList = bmsMdBusinessCategoryService.selectEngineeringBidding();
                String currentUserId = SecurityUtils.getLoginUser().getUser().getUserId();
                for (BmsBusiness business : bmsBusinesss) {
                    BmsProjectDocCatalog bmsProjectDocCatalog = new BmsProjectDocCatalog();
                    if(!(bmsProjectMemberService.isTenderMembers(currentUserId, business)&&engineeringBiddingList.contains(business.getBusinessCategoryId()))){
                        bmsProjectDocCatalog.setBusinessId(business.getGuid());
                        bmsProjectDocCatalog.setParentId("0");
                        List<BmsProjectDocCatalog> bmsProjectDocCatalogs = bmsProjectDocCatalogService.selectBmsProjectDocCatalogList(bmsProjectDocCatalog);
                        if (bmsProjectDocCatalogs != null && bmsProjectDocCatalogs.size() > 0) {
                            bmsProjectDocCatalogs.forEach(item -> {
                                bmsProjectDoc.setCatalogId(item.getGuid());
                                bmsProjectDocService.parsingParamBmsProjectDoc(bmsProjectDoc);
                                item.setCounts(bmsProjectDocService.countProjectDocCatalog(bmsProjectDoc));
                                item.setIsEdit(null);
                            });
                        }
                        treeSelectNews.addAll(bmsProjectDocCatalogs.stream().map(TreeSelectNew::new).collect(Collectors.toList()));
                    }
                }
                trees.addAll(treeSelectNews);
            }else{
                BmsProjectDocCatalog docCatalog = bmsProjectDocCatalogService.selectBmsProjectDocCatalogByGuid(bmsProjectDoc.getCatalogId());
                bmsProjectDoc.setBusinessId(docCatalog.getBusinessId());
                List<BmsProjectDocCatalog> bmsProjectDocCatalogs = bmsProjectDocService.getProjectDocCatalogChildren(bmsProjectDoc);
                trees.addAll(bmsProjectDocCatalogService.buildDocCatalogTreeSelect(bmsProjectDocCatalogs));
            }
        }
        return AjaxResult.success(trees);
    }
}
